package com.it.btyw.modules.user.viewmodel

import LoginVo
import com.it.common.bean.CommonBean
import com.it.common.livedata.UnPeekLiveData
import com.it.common.utils.MD5Utils
import com.it.common.utils.isNotEmpty
import com.it.data.base.BaseViewModel
import com.it.data.manager.AppCacheManager
import com.it.data.network.Api
import com.it.data.network.req.LoginDto
import com.tencent.mmkv.MMKV

class LoginViewModel : BaseViewModel() {
    val loginLiveData by lazy { UnPeekLiveData<CommonBean<LoginVo>>() }

    /**
     * 登录
     * @param loginName String 用户名
     * @param password String 密码
     */
    fun login(loginName: String, password: String) {
        val dto = LoginDto(
            loginName = loginName,
            password = MD5Utils.md5(password),
        )
        requestCommit(request = {
            Api.apiClient().login(dto)
        }, resp = {
            if (it.result && it.data.isNotEmpty()) {
                MMKV.defaultMMKV().encode(AppCacheManager.KEY_TOKEN, it.data?.token)
                MMKV.defaultMMKV().encode(AppCacheManager.KEY_LOGIN_DATA, it.data)
            }
            loginLiveData.postValue(it)
        })
    }


}